<script setup lang="ts">
import Design from "@/views/activity/activityManage/ActivityTempl.vue";
import {
  getTemplateInfoApi,
  saveOrUpdateTemplateApi,
  pageOfTemplateTypeApi,
} from "@/api/activity";
import { componentList } from "@/views/activity/activityManage/components/config";
const route = useRoute(),
  router = useRouter();
const iframeLoading = ref(false),
  templateReady = ref(false),
  templateConfig = ref<Array<any>>([]),
  saveloading = ref(false),
  dialogVisible = ref(false),
  dialogTitle = ref(""),
  classifyList = ref<Array<any>>([]),
  form = ref<any>({ cover: "" });

const designRef = ref(),
  editFormRef = ref();

let templateDetail: any = null,
  rules = {
    name: [
      { required: true, message: "模板名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "模板名称请限制在2至20个字符以内",
        trigger: "blur",
      },
    ],
    activityTemplateTypeId: [
      { required: true, message: "请选择模板类型", trigger: "change" },
    ],
    cover: [{ required: true, message: "请上传模板封面", trigger: "change" }],
  };

const templateId = computed(() => {
  return route.params.id || "";
});

const getTemplateDetail = async () => {
  iframeLoading.value = true;
  const rs = await getTemplateInfoApi({
    id: templateId.value,
  });
  if (rs.code == 200) {
    templateDetail = rs.payload;
    let _templateConfig = [];
    _templateConfig.push({
      pageType: "Home",
      pageName: "首页",
      configList: rs.payload.templateConfig
        ? JSON.parse(rs.payload.templateConfig)
        : [],
    });
    if (rs.payload.subTemplateConfig) {
      _templateConfig = _templateConfig.concat(
        JSON.parse(rs.payload.subTemplateConfig)
      );
    }
    templateConfig.value = _templateConfig;
    templateReady.value = true;
  }
  iframeLoading.value = false;
};

const getClassify = async () => {
  const rs = await pageOfTemplateTypeApi({ currentPage: 1, showCount: -1 });
  if (rs.code == 200) {
    classifyList.value = rs.payload;
  }
};

const addTemplate = (back: boolean) => {
  if (editFormRef.value) editFormRef.value.resetFields();
  form.value = { cover: "", back };
  dialogTitle.value = "新增模板";
  dialogVisible.value = true;
};

const editTemplate = (back: boolean) => {
  form.value = {
    ...templateDetail,
    back,
  };
  dialogTitle.value = `编辑模板【${form.value.name}】`;
  dialogVisible.value = true;
};

const saveTemplate = async (back: boolean) => {
  try {
    
    if(!getActivityType(templateConfig.value[0].configList)) {
      ElMessage.warning('请添加活动组件')
      return
    }
    templateConfig.value = await designRef.value.save();
    if (!templateDetail || templateDetail.id === "") addTemplate(back);
    else editTemplate(back);
  } catch (e) {}
};

const handleGeneratePoster = () => {
  form.value.generateLoading = true;
  designRef.value.generatePoster();
};

const updatePoster = (cover: string) => {
  form.value.generateLoading = false;
  form.value.cover = cover;
};

const goBack = (showTip: boolean) => {
  if (showTip) {
    ElMessageBox.confirm("系统可能不会保存您所做的更改", "确认离开此页面？", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      router.replace({ name: "ActivityTemplate" });
    });
  } else router.replace({ name: "ActivityTemplate" });
};

const submit = async () => {
  editFormRef.value.validate(async (valid: any) => {
    if (valid) {
      saveloading.value = true;
      let _templateConfig = [],
        _subTemplateConfig = [];
      for (let i = 0; i < templateConfig.value.length; i++) {
        if (templateConfig.value[i].pageType === "Home")
          _templateConfig = templateConfig.value[i].configList;
        else _subTemplateConfig.push(templateConfig.value[i]);
      }
      const rs = await saveOrUpdateTemplateApi({
        ...form.value,
        templateConfig: JSON.stringify(_templateConfig),
        subTemplateConfig: JSON.stringify(_subTemplateConfig),
      });
      if (rs.code == 200) {
        templateDetail = { ...form.value, id: rs.payload.id };
        history.replaceState(
          null,
          "活动模板",
          `#/activity/templateMng/design/${rs.payload.id}`
        );
        ElNotification.success({
          message: "保存成功",
        });
        dialogVisible.value = false;
        if (form.value.back) goBack(false);
      }
      saveloading.value = false;
    } else {
    }
  });
};

const getActivityType = (configList: any)=>{
  if(!configList.length) {
    return false
  }
  let typeDataList = ['lotteryComps','interactionComps','taskComps',"specialSaleComps"] //和 抽奖 任务 互动组件类型保持一至 参考config.js文件
  let componentTypeList = [] as any
  componentList.forEach(item=>{
    if(typeDataList.includes(item.type)) {
      item.components.forEach(el=>{
        componentTypeList.push(el.type)
      })
    }
  })
  let isExist = false
  configList.find((item: any)=>{
      if(componentTypeList.includes(item.type)){
        isExist = true
      }  
    })
  return isExist
  
}
provide("updatePoster", updatePoster);

onMounted(() => {
  if (templateId.value !== "") getTemplateDetail();
  else {
    templateReady.value = true;
    templateConfig.value = [
      {
        pageType: "Home",
        pageName: "首页",
        configList: [],
      },
    ];
  }
  getClassify();
});
</script>
<template>
  <MainContent
    class="main-container"
    back
    :backFunc="true"
    title="营销模板"
    :defaultContentSlot="false"
    @back="goBack(true)"
  >
    <template #extra>
      <el-button
        type="primary"
        @click="saveTemplate(false)"
        :loading="saveloading"
        >保存</el-button
      >
      <el-button
        type="primary"
        @click="saveTemplate(true)"
        :loading="saveloading"
        >保存并退出</el-button
      >
    </template>
    <div class="iframe-contain">
      <div class="iframe">
        <Design ref="designRef" v-model="templateConfig" />
      </div>
    </div>
  </MainContent>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
    <el-form :model="form" ref="editFormRef" :rules="rules" label-width="auto">
      <el-form-item label="模板名称:" prop="name">
        <el-input
          v-model.trim="form.name"
          placeholder="请输入模板名称"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="模板类型:" prop="activityTemplateTypeId">
        <el-select
          v-model="form.activityTemplateTypeId"
          placeholder="请选择模板类型"
        >
          <el-option
            v-for="item in classifyList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模板封面:" prop="cover">
        <Upload v-model="form.cover" list-type="picture-card">
          <el-icon>
            <Plus />
          </el-icon>
        </Upload>
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="handleGeneratePoster"
          :loading="form.generateLoading"
          >点击生成</el-button
        >
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submit" :loading="saveloading"
        >保存</el-button
      >
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.main-container {
  :deep(.white) {
    padding: 0 !important;
  }
}
.iframe-contain {
  height: calc(100vh - 100px);
  overflow: auto;
}
.iframe {
  width: 100%;
  min-width: 1360px;
  height: 100%;
  min-height: 655px;
  display: block;
  border: unset;
  margin: unset;
  padding: unset;
  :deep(.templ-container) {
    height: 100% !important;
  }
}
</style>
